/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-14 20:10:32
 */
import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserInfoStore } from './stores/userInfo'
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title as string)
  const useInfoStore = useUserInfoStore()
  const token = useInfoStore.token
  if (token) {
    // token存在
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      const flag = !!useInfoStore.userInfo.name
      if (flag) {
        next()
        NProgress.done()
      } else {
        try {
          await useInfoStore.getInfo()
          next(to)
          NProgress.done()
        } catch (error) {
          useInfoStore.reset()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // token不存在
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
